﻿using System;
using System.Linq;
using System.Text;
using SuperX.Common.Log;
using SuperSocket.Common;
using SuperSocket.Facility.Protocol;

namespace SuperX.SuperSocket.Socket.Message
{
    public class MessageReceiveFilter : FixedHeaderReceiveFilter<MessageRequestInfo>
    {
        public MessageReceiveFilter() : base(SocketMessage.FixHeaderLength)
        {
        }

        protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
        {
            var len = BitConverter.ToInt32(header, offset + 5);
            var totalLength = len / 256 + len % 256 + BitConverter.ToInt32(header, offset + 9);
            return totalLength;
        }

        protected override MessageRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
        {
            byte[] headerBytes = header.Array;
            SocketMessage message = new SocketMessage();
            if (headerBytes[0] != 67 || headerBytes[1] != 81)
            {
                message.Error = "Fix header error";
                message.IsError = true;
                Logger.Info($"ResolveRequestInfo {message.Error}");
            }
            else
            {
                var headerLength = (int)(BitConverter.ToUInt32(headerBytes, 5) / 256);
                var cmdLength = (int)(BitConverter.ToUInt32(headerBytes, 5) % 256);
                var bodyLength = BitConverter.ToInt32(headerBytes, 9);
                message.Command = Encoding.UTF8.GetString(bodyBuffer.CloneRange(offset, cmdLength));
                message.Header = Encoding.UTF8.GetString(bodyBuffer.CloneRange(offset + cmdLength, headerLength));
                message.Body = bodyBuffer.CloneRange(offset + cmdLength + headerLength, bodyLength);
                //Common.Log.Logger.Info($"ResolveRequestInfo {headerLength} { message.Header} {cmdLength} {message.Command} {bodyLength} {message.BodyLength}");
            }
            return new MessageRequestInfo(message);
        }
    }
}